/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import bean.EditProviderTaskBean;
import bean.LoginActionFormBean;
import bean.MainScheduleTask;
import dao.ActivityHistoryCrud;
import dao.ProviderDao;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.EditProvider;
//import model.ScheduleTaskWindows;
import model.LogFile;
import model.OSDetector;
import model.ScheduledTaskLinux;
import model.ScheduledTaskWindows;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import pojo.Activities;
import pojo.ActivityHistory;
import pojo.Provider;
import pojo.Scheduledata;

/**
 *
 * @author A7med Kotb
 */
//this class for editting provider schedule task
public class EditProviderTask extends org.apache.struts.actions.DispatchAction {
    /* forward name="success" path="" */

    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    //this method to list task data for editting after that
    public ActionForward Edit(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        int taskid = Integer.parseInt(request.getParameter("taskid"));
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        Provider pro = new ProviderDao(getDataSource(request, "MyDS").getConnection()).getById(taskid);
        EditProvider mypro = new EditProvider(getDataSource(request, "MyDS").getConnection());
        Scheduledata scdata = mypro.scheduleInformation(taskid);
        request.setAttribute("data", scdata);
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        String reportDate = df.format(scdata.getStartDate());
        request.setAttribute("startdate", reportDate);
        boolean editresult = activityHistory("Edit Schedule Task Data", request, taskid);
        if (editresult == true) {
            LogFile.log(loginbean.getUserName(), " trying to edit the schedule task data for the provider " + pro.getName());
        } else {
            LogFile.log("System", " Failed to edit in the schedule task data for the provider " + pro.getName());
        }
        return mapping.findForward("edit");
    }

    //this method for updating schedule task data
    public ActionForward Update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        EditProviderTaskBean mst = (EditProviderTaskBean) form;
        Scheduledata sc = new Scheduledata();
        int taskid = Integer.parseInt(mst.getId());
        LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
        sc.setScId(taskid);
        sc.setSchedule(mst.getSchedule());
        sc.setModifier(mst.getModifier());
        sc.setStartDate(mst.getStartDated());
        sc.setStartTime(mst.getStartTime());
        if (mst.getSchedule().equalsIgnoreCase("hourly") || mst.getSchedule().equalsIgnoreCase("daily")) {
            mst.setDay(null);
        }
        if (mst.getNewDays() != null) {
            String[] selectedDays = mst.getNewDays();
            String days = "";
            for (int i = 0; i < selectedDays.length; i++) {
                days += selectedDays[i] + ",";
            }
            int strlen = days.length();
            int lastindex = strlen - 1;
            String taskdays = days.substring(0, lastindex);
            sc.setDay(taskdays);
        } else {
            sc.setDay(mst.getDay());
        }
        if (mst.getNewMonths() != null) {
            String[] selectedMonths = mst.getNewMonths();
            String months = "";
            for (int i = 0; i < selectedMonths.length; i++) {
                months += selectedMonths[i] + ",";
            }
            int monthslen = months.length();
            int lastmonthsindex = monthslen - 1;
            String taskmonths = months.substring(0, lastmonthsindex);
            sc.setMonth(taskmonths);
        } else {
            sc.setMonth(mst.getMonth());
        }
        sc.setIsenable(mst.getIsenable());
        sc.setIsrunning(mst.getIsrunning());
        EditProvider mypro = new EditProvider(getDataSource(request, "MyDS").getConnection());
        mypro.UpdateproviderSchedule(sc);
        Provider pro = mypro.getProviderById(taskid);
        if (OSDetector.isWindows()) {
            new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).deleteAfterUpdate(taskid);
            new ScheduledTaskWindows(getDataSource(request, "MyDS").getConnection()).create(sc, pro.getName());
        }
        if (OSDetector.isUnix()) {
            new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).delete(taskid);
            new ScheduledTaskLinux(getDataSource(request, "MyDS").getConnection()).create(sc, pro.getName());
        }
        return mapping.findForward(SUCCESS);
    }

    //Add Activity to Activity History
    public boolean activityHistory(String activityName, HttpServletRequest request, int taskid) {
        boolean check = false;
        try {
            LoginActionFormBean loginbean = (LoginActionFormBean) request.getSession().getAttribute("LoginActionFormBean");
            ActivityHistory log = new ActivityHistory();
            log.setAdminName(loginbean.getUserName());
            ProviderDao pdao = new ProviderDao(getDataSource(request, "MyDS").getConnection());
            Provider pro = pdao.getById(taskid);
            log.setProviderName(pro.getName());
            log.setStatus("Success");
            log.setLiveServer(null);
            ActivityHistoryCrud ahc = new ActivityHistoryCrud(getDataSource(request, "MyDS").getConnection());
            Activities act = ahc.getByName(activityName);
            log.setActivities(act);
            log.setActivityName(act.getName());
            check = ahc.add(log);
        } catch (SQLException ex) {
            Logger.getLogger(STOperations.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System ", " encountered the following exception during trying to log the data in History table " + ex.getMessage());
        }
        return check;
    }
}
